<?php
defined ( 'BASEPATH' ) or exit ( 'No direct script access allowed' );
/**
 * 微信登录
 * @author chaituan@126.com
 */
use EasyWeChat\Foundation\Application;
class Login extends CI_Controller {
	
	// 注册
	public function index() {
		$this->load->model('admin/User_model');
		
		$data = Posts();
		$code = $data['code'];
		$info = json_decode($data['info'],true);
		
		// 获取授权登录的微信用户信息
		$app = new Application(array('mini_program'=>array('app_id'=>WX_APPID,'secret'=> WX_APPSecret,'token'=>'ctfanqie','aes_key'=>'73133b70e53e46d80')));
		$res = $app->mini_program->sns->getSessionKey($code);
		if(isset($_POST['iv'])&&isset($_POST['ed'])){			
			$ed = $app->mini_program->encryptor->decryptData($res['session_key'],$_POST['iv'],$_POST['ed']);
		}else{
			$ed = '';
		}		
		if ($res['openid']) {
			// 数据库是否存在
			$item = $this->User_model->get_user('openid',$res['openid']);
			if (!$item) {				
				$datas = array (
						'openid' => $res['openid'],
						'thumb' => $info['avatarUrl'],
						'nickname' => set_Nickname($info['nickName']),
						'nicknames' => $info['nickName'],
						'sex' => $info['gender'],
						'unid'=>$ed?$ed['unionId']:'',
						'addtime' => time () 
				);
				$fid = $data['fid'];
				if($fid){
					$fx = $this->User_model->getItem(array('id'=>$fid,'gid'=>2),'id,p_1,p_2');
					if($fx){
						$datas['p_1'] = $fx['id'];
						$datas['p_2'] = $fx['p_1'];
						$datas['p_3'] = $fx['p_2'];
					}
				}
				$userid = $this->User_model->add($datas);
				$item = $this->User_model->getItem("id=$userid");
			}else{
				$userid = $item['id'];
			}
			$this->User_model->set_LoginUser($item);
			AjaxResult(1, '登录成功',array('uid'=>$userid,'sid'=>$this->session->session_id,'userinfo'=>$item));
		} else {
			AjaxResult_error("登录失败");
		}
		
	}

}
